package cn.rongdao.jrkabao.ui.webview;

import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.support.annotation.NonNull;
import android.text.TextUtils;
import android.view.KeyEvent;
import android.webkit.WebView;

import com.mifengkong.frtools.ui.activity.FRStartActivity;
import com.mifengkong.frtools.util.FRString;
import com.mifengkong.frtools.util.FRToast;
import com.mifengkong.frwidget.titlebar.WebViewTitleBarUIComponent;
import com.umeng.socialize.UMShareAPI;

import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import butterknife.BindView;
import cn.mifengkong.appcommon.webview.JsLocalStorageConstantUtil;
import cn.mifengkong.appcommon.webview.uicomponent.WebViewUIComponent;
import cn.rongdao.jrkabao.R;
import cn.rongdao.jrkabao.base.BaseAutoFinishActivity;
import cn.rongdao.jrkabao.constant.InfoConstant;
import cn.rongdao.jrkabao.ui.IdentificationVerificate.IdentifySuccessEvent;
import cn.rongdao.jrkabao.ui.cashadvance.CashAdvanceSuccessActivity;
import cn.rongdao.jrkabao.ui.cashadvance.event.ChangeCreditCardEvent;
import cn.rongdao.jrkabao.ui.cashadvance.event.ChangeDepositCardEvent;

import static com.mifengkong.frwidget.webview.MyWebChromeClient.FILECHOOSER_RESULTCODE;

/**
 *
 */

public class WebViewActivity extends BaseAutoFinishActivity {

    private String mOrderNum;//取现所要用到的订单编号

    public static void startWithProductId(Context context, String url, String productId) {
        Bundle bundle = new Bundle();
        bundle.putString(URL, url);
        bundle.putString(InfoConstant.PRODUCT_ID, productId);
        FRStartActivity.start(context, WebViewActivity.class, bundle, FRStartActivity.DEFAULT_FLAGS);
    }

    public static void startWithOrderNum(Context context, String url, String orderNum) {
        Bundle bundle = new Bundle();
        bundle.putString(URL, url);
        bundle.putString(InfoConstant.ORDER_NUM, orderNum);
        FRStartActivity.start(context, WebViewActivity.class, bundle);
    }

    public static void start(Context context, String url) {
        startWithOrderNum(context, url, "");
    }

    protected static final String URL = "url";

    @BindView(R.id.aw_webview_uicomponent)
    WebViewUIComponent webViewUIComponent;
    @BindView(R.id.lw_titlebar)
    WebViewTitleBarUIComponent titleBarUIComponent;
    private WebViewHelper webViewHelper;
    protected String mProductId;

    @Override
    protected int layoutRes() {
        return R.layout.activity_webview;
    }

    @Override
    protected void initView() {
        super.initView();
        setAutoHideSoftInput(true);
        webViewHelper = new WebViewHelper(this, webViewUIComponent, titleBarUIComponent);
        String url = getIntent().getStringExtra(URL);
        mOrderNum = getIntent().getStringExtra(InfoConstant.ORDER_NUM);
        if (!FRString.isEmpty(mOrderNum)) {
            webViewUIComponent.showLoading();
        }
        initTitleBar();
        webViewHelper.loadUrlAndSetLocalStorage(url);
        initListener();
    }

    private void initListener() {
        webViewHelper.setOnWebViewCallBack(new WebViewHelper.OnWebViewCallBack() {
            @Override
            public boolean shouldOverrideUrlLoading(WebView view, String urlString) {
                //获取公积金的额度
                if (CheckPublicFundLimit(urlString)) {
                    return true;
                }
                if (zhimaCheckSuccess(view, urlString)) {
                    return true;
                }
                if (activityFinish(urlString)) {
                    return true;
                }
                if (cashForUnionPayReback(urlString)) {
                    return true;
                }
                if (urlString.startsWith(InfoConstant.YY_RETURN_DATA) || urlString.startsWith(InfoConstant.YY_OVERRIDE_SCHEMA)) {//如果捕捉到的是jsBridge的两个头地址，就不执行
                    return true;
                }
                return false;
            }

            @Override
            public void onPageFinished(WebView view, String url) {
                if (!FRString.isEmpty(mOrderNum)) {
                    webViewUIComponent.hideLoading();
                }
                if (!FRString.isEmpty(url) && !FRString.isEmpty(mOrderNum) && isUrlFromHanYin(url)) {
                    webViewUIComponent.loadUrlAndData(JsLocalStorageConstantUtil.getCashFailureMessageJs(url));
                }
            }
        });
    }

    public boolean isUrlFromHanYin(String url) {
        return !FRString.isEmpty(url) && (url.contains(getString(R.string.cashadvancejs)) || url.contains(getString(R.string.cashadvancejs_test)) || url.contains(getString(R.string.cashadvancejs_error)) || url.contains(getString(R.string.cashadvancejs_error_test)));
    }

    /**
     * 是否为银联的回调接口
     *
     * @param url
     * @return
     */
    private boolean cashForUnionPayReback(String url) {
        if (!FRString.isEmpty(url) && url.contains(InfoConstant.UNIONPAY_REBACK)) {
            if (TextUtils.isEmpty(mOrderNum)) {
                FRToast.showToastSafe("获取订单编号失败，退出APP重试");
                return true;
            }
            CashAdvanceSuccessActivity.start(this, mOrderNum, false);
            finish();
            return true;
        }
        return false;
    }

    private boolean activityFinish(String url) {
        if (url.equals(InfoConstant.HASPLAYEDURL)) {//活动界面，第二次点击抽奖抓取的URL
            finish();
            return true;
        }
        return false;
    }

    private boolean zhimaCheckSuccess(WebView view, String url) {
        if (url.contains(InfoConstant.ZHIMACALLBACKURL)) {
            FRToast.showToastSafe("芝麻信用授权成功,1秒后跳回原来的页面");
            new Handler().postDelayed(new Runnable() {
                @Override
                public void run() {
                    finish();
                }
            }, 1000);
            view.loadUrl(url);
            return true;
        }
        return false;
    }

    private void initTitleBar() {
        webViewHelper.initTitleBar(R.drawable.icon_close_white, R.drawable.icon_refresh);
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK) {
            if (webViewUIComponent.isWebViewCanGoBack()) {
                webViewUIComponent.goBack();
                return true;
            }
        }
        webViewHelper.closeActivity();
        return super.onKeyDown(keyCode, event);
    }

    @Subscribe(threadMode = ThreadMode.MAIN) //在ui线程执行
    public void identifySuccessEventMessage(IdentifySuccessEvent identifySuccessEvent) {
        webViewHelper.refreshLoad();
    }

    @Subscribe(threadMode = ThreadMode.MAIN) //在ui线程执行
    public void changeCreditCardEventMessage(ChangeCreditCardEvent changeCreditCardEvent) {
        webViewHelper.refreshLoad();
    }

    @Subscribe(threadMode = ThreadMode.MAIN) //在ui线程执行
    public void changeDepositCardEventMessage(ChangeDepositCardEvent changeDepositCardEvent) {
        webViewHelper.refreshLoad();
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        webViewHelper.onRequestPermissionsResult(requestCode, permissions, grantResults);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        UMShareAPI.get(this).onActivityResult(requestCode, resultCode, data);
        webViewHelper.onActivityResult(requestCode,resultCode,data);
        if (requestCode == FILECHOOSER_RESULTCODE) {
            webViewUIComponent.onActivityResult(requestCode, resultCode, data);
        }
    }

    private boolean CheckPublicFundLimit(String urlString) {
        if (urlString.contains(InfoConstant.FINISHURL)) {
            if (urlString.contains(InfoConstant.WACAIFUNDURL)) {
                getUserFundData();
            } else {
                finish();
            }
            return true;
        }
        return false;
    }

    /**
     * 这个方法在子类中也有不同的实现，主要是给公积金页面使用的
     */
    protected void getUserFundData() {
        finish();
    }

    @Override
    public void onStop() {
        super.onStop();
        webViewHelper.onStop();
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        webViewHelper.onDestroy();
    }
}